/**
 * 缓存管理
 * 使得本地持久缓存规范化存储，支持设置缓存有效时间
 * @Author: liruilin 1443254530@qq.com
 * @Date: 2025-4-8 14:02:26
 * @LastEditors: liruilin 1443254530@qq.com
 * @FilePath: libs\common\storage.js
 */

class Storage{
    #_PREFIX_KEY = 'APP-STORAGE.'
    /**
     * 设置缓存
     * @param {Object} key
     * @param {Object} data
     * @param {Object} duration 缓存有效时间，毫秒，从设置缓存开始计算，获取时判断
     */
    set(key, data, duration){
        const storageData = {
            data,
            setTime: (new Date()).getTime(),
            duration
        }
        uni.setStorageSync(this.#_PREFIX_KEY + key, storageData)
    }
    /**
     * 获取缓存
     * @param {Object} key
     * @return {Object} { setTime, duration, data }
     */
    get(key){
        const storageData = uni.getStorageSync(this.#_PREFIX_KEY + key)
        if(storageData){
            const { setTime, duration, data } = storageData
            // 设置过期时间，判断
            if(duration && (setTime + duration) < (new Date()).getTime()){
                this.clear(this.#_PREFIX_KEY + key)
                return null
            }
            return storageData
        }else {
            return null
        }
    }
    /**
     * 清除缓存
     * @param {Object} key
     */
    clear(key){
        uni.clearStorageSync(this.#_PREFIX_KEY + key)
    }
}

export default (new Storage())